package com.study.common;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.Locale;

/**
 * web相关工具类
 *
 * @author niuxiaolong
 * @version 2.0, 2017/6/19
 * @since 2.0
 */
@Component
public class WebUtils {
    private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);

    private static final String XML_HTTP_REQUEST = "XMLHttpRequest";
    private static final String X_REQUESTED_WITH = "X-Requested-With";

    @Autowired(required = false)
    private HttpServletRequest request;

    public boolean isAjax() {
        String requestedWith = request.getHeader(X_REQUESTED_WITH);

        return requestedWith != null && requestedWith.contains(XML_HTTP_REQUEST);
    }

    public String getIP4() {
        String ip = request.getHeader("x-forwarded-for");

        if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (Strings.isNullOrEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }

    public <T> void responseJson(Result<T> result, ServletResponse response) {
        MessageSource messageSource = SpringContextHolder.getBean("messageSource", MessageSource.class);
        result.setMessage(messageSource.getMessage(result.getCode(), null, Locale.CHINA));
        response.setContentType("text/plain;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.print(JSON.toJSONString(result));
            out.flush();
        } catch (Exception e) {
            logger.error("过滤器json反回信息输出异常：{}", result, e);
        }
    }
}
